<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * 站点管理控制器
 * @author 66diqiu-li
 *
 */
class Admin_Site_module extends CI_Module {

    public $Site_model;

	/**
	 * 
	 * 构造函数
	 */
    public function __construct(){
        error_reporting(E_ALL ^ E_NOTICE);
    	parent::__construct();
        $adminid = $this->session->userdata('admin_user_id');

        /*全局管理员才有这个功能*/
        if(!in_array($adminid, array(
            '11'  //全局管理员
        )))
        {
            redirect('admin/index');
        }

        $this->load->model('admin.Site_model');

        $this->load->model('admin.Adminuser_model');
        $this->load->model('admin.Adminrole_model');
        $this->load->model('expert.Expert_model');
        $this->load->model('admin.Upload_model');
        $this->load->config('template');
    }
    
    function index(){
        $data['site_list'] = $this->Site_model->get_site_list(null, null, intval($_GET['linshi']));
        foreach ($data['site_list'] as $k => $v) {
            $data['site_list'][$k]['site_template'] = $tpl = $this->Shopconfig_model->get_key_value($v['sid'], 'site_template');
            if(!$tpl){
                $tpl = 'bz06';
            }
            $data['site_list'][$k]['site_templatename'] = $this->config->config['template'][$tpl]['name'];
        }

        $this->load->view('site/index', $data);
    }

    public function add()
    {
        if($_POST['multi'] && $rows = $_POST['rows']){
            $tpls = $insertdata = array();
            $founders = $rows['founder'];
            $maxport = $this->Site_model->get_max_port();
            foreach ($founders as $k => $founder) {
                $pwd = trim($rows['password'][$k]) ? trim($rows['password'][$k]) : '123456';
                $url = rtrim($rows['url'][$k], '/');
                $type = trim($rows['type'][$k]);
                $name = trim($rows['name'][$k]);
                if(empty($founder)) {
                    $this->error('站长账号不能为空！', '', true);
                }
                if(empty($url)) {
                    $url = 'http://www.66diqiu.com:' . (++$maxport);
//                    $this->error('网址不能为空！', '', true);
                }
                if(!$this->checksite($url, 1)){
                    $this->error('网址已经存在！'.$url, '', true);
                }
                if(empty($name)) {
                    $this->error('网站名称！', '', true);
                }

                $data = array(
                    'founder' => trim($founder),
                    'pwd' => $pwd,
                    'url' => $url,
                    'type' => $type,
                    'name' => $name,
                    'status' => 1,
                );
                if($rows['sid'][$k]){
                    $data['sid'] = intval($rows['sid'][$k]);
                }
                if($rows['site_template'][$k]){
                    $data['site_template'] = $rows['site_template'][$k];
                }
                $insertdata[] = $data;
            }
            foreach ($insertdata as $row) {
                $this->do_insert($row);
            }

            $this->success('站点添加成功！请添加配置nginx ：/usr/local/nginx/sbin/nginx -s reload', site_url('admin/site/index'), true);
        }
        $this->load->view('site/add');
    }

    public function edit()
    {
        $url = trim($_GET['url']);
        if(!empty($_POST['row']))
        {
            $row = $_POST['row'];
            $row['url'] = rtrim($row['url'], '/');
            $sid = intval($_POST['sid']);
            $info = $this->Site_model->get_row(array('sid' => $sid));
            if(!$info){
                $this->error('非法操作', '', true);
            }
            $res = $this->Site_model->edit_row($row, array('sid' => $sid));
            if($res){

                $info = parse_url($row['url']);
                @$server_name = $info['host'] == 'www.66diqiu.com' ? '127.0.0.1' : $info['host'];
                $port = isset($info['port']) ? $info['port'] : '80';
                $filename = $server_name . '_'. $port .'.conf';
                if(!is_file('/usr/local/nginx/conf/vhost/'.$filename)) {
                    $conf = <<<CONF
server
{
    listen      $port;
    server_name $server_name;
    index index.html index.htm index.php default.html default.htm default.php;
    root  /home/66root/site;

    location /
    {
        if (!-e \$request_filename)
        {
            rewrite  ^/(.*)$  /index.php/$1  last;
            break;
        }
    }
    location ~ [^/]\.php(/|$)
    {
        # comment try_files \$uri =404; to enable pathinfo
        # try_files \$uri =404;
        fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set \$path_info \$fastcgi_path_info;
        fastcgi_param PATH_INFO       \$path_info;
        try_files \$fastcgi_script_name =404;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
    }

    location ~ .*\.(js|css)?$
    {
        expires      12h;
    }

    #access_log  /home/wwwlogs/8018.log  access;
    access_log off;
}
CONF;
                    @file_put_contents('application/cache/' . $filename, $conf);
                    @copy('application/cache/' . $filename, '/usr/local/nginx/conf/vhost/' . $filename);
                    @unlink('application/cache/' . $filename);
                }

                $data = array();
                $data['name']     = $row['founder'];
                if($password = trim($_POST['admin']['password']))
                {
                    $data['password'] = md5($password);
                }
                $this->Adminuser_model->edit_row($data, 'name=\''.addslashes($info['founder']).'\'', true);

                $site_template = trim($_POST['configs']['site_template']);
                if(!empty($site_template)){
                    $this->Shopconfig_model->update_batch($sid, array(
                        'site_template' => $site_template,
                    ));
                }

                $this->success('修改成功！', '',  true);
            }
        }

        $site_info = $this->Site_model->get_site_info($url);
        $basice_info = $this->Shopconfig_model->set_basice_info($this->Shopconfig_model->get_info($site_info['sid']));

        $site_info['template'] = $basice_info['site_template'];
        $this->load->view('site/add',
            array(
                'info' => $site_info
            ));
    }


    public function do_insert($row){
        $site_template = $row['site_template'];
        unset($row['site_template']);

        $sid = $this->Site_model->add_row($row);
        $GLOBALS['sid'] = $sid;
        if(!$sid){
            $this->error('站点添加失败！', '', true);
        }

        if($site_template){
            $this->Shopconfig_model->update_batch($sid, array(
                'site_template' => $site_template,
            ));
        }

        $current = date('Y-m-d H:i:s');
        /*添加角色*/
        $super_role_id = $this->Adminrole_model->add_row(array(
            'name' => '超级管理员',
            'status' => 1,
            'remark' => '拥有网站最高管理员权限！',
            'add_time' => $current,
            'edit_time' => $current,
        ));

        /*添加达人角色*/

        $this->Adminrole_model->add_row(array(
            'name' => '达人',
            'status' => 1,
            'remark' => '达人！',
            'add_time' => $current,
            'edit_time' => $current,
        ));

        $data = array();
        $data['name']     = $row['founder'];
        $data['password'] = md5($row['pwd']);
        $data['role_id']  = $super_role_id;
        $data['add_time'] = $current;
        $id = $this->Adminuser_model->add_row($data);


        // 添加积分规则
        $rule_table = $this->db->dbprefix('user_integral_rule');
        $rule_data = array(
            array('sid'=>$sid,'rulename'=>'登陆','action'=>'login','integral'=>'1'),
            array('sid'=>$sid,'rulename'=>'注册','action'=>'register','integral'=>'1')
        );
        $this->db->insert_batch($rule_table, $rule_data);

        $info = parse_url($row['url']);
        @$server_name = $info['host'] == 'www.66diqiu.com' ? '127.0.0.1' : $info['host'];
        $port = isset($info['port']) ? $info['port'] : '80';
        $filename = $server_name . '_'. $port .'.conf';
        if($id)
        {
            $conf = <<<CONF
server
{
    listen      $port;
    server_name $server_name;
    index index.html index.htm index.php default.html default.htm default.php;
    root  /home/66root/site;

    location /
    {
        if (!-e \$request_filename)
        {
            rewrite  ^/(.*)$  /index.php/$1  last;
            break;
        }
    }
    location ~ [^/]\.php(/|$)
    {
        # comment try_files \$uri =404; to enable pathinfo
        # try_files \$uri =404;
        fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set \$path_info \$fastcgi_path_info;
        fastcgi_param PATH_INFO       \$path_info;
        try_files \$fastcgi_script_name =404;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
    }

    location ~ .*\.(js|css)?$
    {
        expires      12h;
    }

    #access_log  /home/wwwlogs/8018.log  access;
    access_log off;
}
CONF;
            if(strpos($server_name, 'lxs.66diqiu.com') === false && strpos($server_name, 'v.zhanglvbao.com') === false ){
                @file_put_contents('application/cache/'.$filename, $conf);
                @copy('application/cache/'.$filename, '/usr/local/nginx/conf/vhost/'.$filename);
                @unlink('application/cache/'.$filename);
            }
        }
        return true;
    }

    function checksite($url = '', $return = 0){
        if(!$url){
            $arg_get = $this->input->get();
            $url = $arg_get['rows']['url'][0];
        }
        $row = $this->Site_model->get_row(array('url'=>$url));
        if($return){
            if(!empty($row)){
                return false;
            }else{
                return true;
            }
        }else{
            if(!empty($row)){
                $this->ajaxReturn('网址已存在!');
            }else{
                $this->ajaxReturn(true);
            }
        }
    }
}